<template>  <div class="inventory-container">    <!-- 预警消息 -->
    <div v-if="filteredWarnings.length > 0" class="warning-section">
      <div v-if="showWarnings">
        <el-alert
          type="warning"
          :closable="true"
          @close="showWarnings = false"
          class="mb-20"
        >
          <div class="warning-list">
            <div class="warning-header">
              <el-icon><warning-filled /></el-icon>
              <span>当前有 {{ filteredWarnings.length }} 个库存预警</span>
            </div>
            <div v-for="(warn, index) in filteredWarnings" :key="index" class="warning-item">
              <el-tag 
                :type="warn.quantity < warn.item.minimumStock ? 'danger' : 'warning'"
                size="small"
              >
                {{ warn.quantity < warn.item.minimumStock ? '库存不足' : '库存过高' }}
              </el-tag>
              <span class="warning-item-name">{{ warn.item.itemName }}</span>
              <span class="warning-item-warehouse">{{ warn.warehouse.warehouseName }}</span>
              <span class="warning-item-quantity">
                当前: {{ warn.quantity }}
                {{ 
                  warn.quantity < warn.item.minimumStock ? 
                  `(低于最低库存: ${warn.item.minimumStock})` : 
                  warn.item.maximumStock !== null && warn.quantity > warn.item.maximumStock ? 
                  `(超过最高库存: ${warn.item.maximumStock})` : ''
                }}
              </span>
            </div>
          </div>
        </el-alert>
      </div>      <div v-else>
        <el-button 
          type="warning" 
          :icon="IconWarning" 
          class="mb-20"
          @click="showWarnings = true"
        >
          显示库存预警 ({{ filteredWarnings.length }})
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-select
        v-model="searchForm.itemId"
        placeholder="请选择物品"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="item in itemOptions"
          :key="item.itemId"
          :label="item.itemName"
          :value="item.itemId"
        />
      </el-select>

      <el-select
        v-model="searchForm.warehouseId"
        placeholder="请选择仓库"
        clearable
        class="search-select"
        style="width: 180px"
      >
        <el-option
          v-for="warehouse in warehouseOptions"
          :key="warehouse.warehouseId"
          :label="warehouse.warehouseName"
          :value="warehouse.warehouseId"
        />
      </el-select>

      <el-button type="primary" :icon="IconSearch" @click="handleSearch">搜索</el-button>
    </div>

    <el-table :data="tableData" border v-loading="loading" style="width: 100%" class="inventory-table">
      <el-table-column prop="inventoryId" label="库存ID" width="80" />
      <el-table-column label="物品信息" width="200">
        <template #default="{ row }">
          <div>
            <div>名称：{{ row.item.itemName }}</div>
            <div>最低库存：{{ row.item.minimumStock }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="仓库信息" width="150">
        <template #default="{ row }">
          <div>{{ row.warehouse.warehouseName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="当前库存" width="150">
        <template #default="{ row }">
          <div class="stock-cell">
            <span :class="{
              'stock-value': true,
              'warning-low': row.quantity < row.item.minimumStock,
              'warning-high': row.item.maximumStock !== null && row.quantity > row.item.maximumStock
            }">
              {{ row.quantity }}
            </span>
            <el-tooltip
              v-if="row.quantity < row.item.minimumStock || (row.item.maximumStock !== null && row.quantity > row.item.maximumStock)"
              :content="
                row.quantity < row.item.minimumStock ? 
                `库存不足 (低于最低库存: ${row.item.minimumStock})` : 
                `库存过高 (超过最高库存: ${row.item.maximumStock})`"
              placement="top"
            >
              <el-tag
                :type="row.quantity < row.item.minimumStock ? 'danger' : 'warning'"
                size="small"
                class="warning-tag"
              >
                {{ row.quantity < row.item.minimumStock ? '低' : '高' }}
              </el-tag>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价" width="120">
        <template #default="{ row }">
          ¥{{ (row.totalValue / row.quantity).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalValue" label="总价值" width="120">
        <template #default="{ row }">
          ¥{{ (row.totalValue ?? 0).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastCheckTime" label="最后盘点时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="IconCheck" circle @click="handleCheck(row)" />
          <el-button type="info" :icon="IconView" circle @click="handleDetail(row)" />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="!total"
      />
    </div>

    <!-- 盘点对话框 -->
    <el-dialog
      v-model="checkDialogVisible"
      title="库存盘点"
      width="500px"
    >
      <el-form :model="checkForm" label-width="100px">
        <el-form-item label="当前库存">
          <span>{{ currentInventory?.quantity }}</span>
        </el-form-item>
        <el-form-item label="实际库存" required>
          <el-input-number
            v-model="checkForm.quantity"
            :min="0"
            :controls="false"
            placeholder="请输入实际库存数量"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="checkForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCheck">确认盘点</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="库存详情"
      width="600px"
    >
      <div v-loading="detailLoading">
        <template v-if="currentInventory">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="库存ID">{{ currentInventory.inventoryId }}</el-descriptions-item>
            <el-descriptions-item label="物品名称">{{ currentInventory.item.itemName }}</el-descriptions-item>
            <el-descriptions-item label="仓库名称">{{ currentInventory.warehouse.warehouseName }}</el-descriptions-item>
            <el-descriptions-item label="当前库存">{{ currentInventory.quantity }}</el-descriptions-item>
            <el-descriptions-item label="单价">¥{{ currentInventory.unitPrice?.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="总价值">¥{{ currentInventory.totalValue?.toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="最后盘点时间">{{ currentInventory.lastCheckTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentInventory.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentInventory.updatedAt }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search as IconSearch, View as IconView, Check as IconCheck, Warning as IconWarning, WarningFilled } from '@element-plus/icons-vue'
import { getInventoryList, getInventoryById, checkInventory, getInventoryWarnings } from '@/api/inventory'
import itemApi from '@/api/item'
import warehouseApi from '@/api/warehouse'
import type { ItemInfo } from '@/api/item'
import type { WarehouseInfo } from '@/api/warehouse'
import type { InventoryInfo, InventoryWarning } from '@/api/inventory'

// 表格数据
const tableData = ref<InventoryInfo[]>([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  itemId: undefined as number | undefined,
  warehouseId: undefined as number | undefined,
  lowStock: false
})

// 物品和仓库选项
const itemOptions = ref<ItemInfo[]>([])
const warehouseOptions = ref<WarehouseInfo[]>([])

// 盘点相关
const checkDialogVisible = ref(false)
const checkForm = reactive({
  quantity: 0,
  notes: ''
})
const currentInventory = ref<InventoryInfo | null>(null)

// 详情相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)

// 库存预警相关
const warnings = ref<InventoryWarning[]>([])
const warningLoading = ref(false)
const showWarnings = ref(true)

// 过滤出需要预警的记录
const filteredWarnings = computed(() => {
  return warnings.value.filter(warn => 
    warn.quantity < warn.item.minimumStock || 
    (warn.item.maximumStock !== null && warn.quantity > warn.item.maximumStock))
})

// 获取库存列表
const fetchInventoryList = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await getInventoryList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 获取物品选项
const getItemOptions = async () => {
  try {
    const res = await itemApi.getItemList({ page: 1, pageSize: 1000 })
    itemOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 获取仓库选项
const getWarehouseOptions = async () => {
  try {
    const res = await warehouseApi.getWarehouseList({ pageNum: 1, pageSize: 1000 })
    warehouseOptions.value = res.data.list
  } catch (error) {
    // 忽略错误，不影响主流程
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchInventoryList()
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchInventoryList()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  fetchInventoryList()
}

// 盘点
const handleCheck = (row: InventoryInfo) => {
  currentInventory.value = row
  checkForm.quantity = row.quantity
  checkForm.notes = ''
  checkDialogVisible.value = true
}

const submitCheck = async () => {
  if (!currentInventory.value) return
  try {
    await checkInventory(currentInventory.value.inventoryId, checkForm)
    ElMessage.success('盘点成功')
    checkDialogVisible.value = false
    fetchInventoryList()
  } catch (error) {
    ElMessage.error('盘点失败')
  }
}

// 查看详情
const handleDetail = async (row: InventoryInfo) => {
  detailLoading.value = true
  try {
    const res = await getInventoryById(row.inventoryId)
    currentInventory.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 获取库存预警列表
const fetchInventoryWarnings = async () => {
  warningLoading.value = true
  try {
    const res = await getInventoryWarnings()
    warnings.value = res.data.list
    // 如果有预警信息，默认显示
    if (warnings.value.length > 0) {
      showWarnings.value = true
    }
  } catch (error) {
    ElMessage.error('获取库存预警信息失败')
  } finally {
    warningLoading.value = false
  }
}

// 定时刷新预警信息
const startWarningRefresh = () => {
  setInterval(fetchInventoryWarnings, 5 * 60 * 1000) // 每5分钟刷新一次
}

onMounted(() => {
  getItemOptions()
  getWarehouseOptions()
  fetchInventoryList()
  fetchInventoryWarnings()
  startWarningRefresh()
})
</script>

<style scoped>
.inventory-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-select {
  width: 180px;
}

.inventory-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.warning-section {
  margin-bottom: 20px;
}

.warning-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.warning-list {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.warning-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.warning-item-name {
  font-weight: bold;
  min-width: 120px;
}

.warning-item-warehouse {
  color: var(--el-text-color-secondary);
  min-width: 100px;
}

.warning-item-quantity {
  color: var(--el-text-color-regular);
}

.stock-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stock-value {
  font-weight: bold;
}

.warning-low {
  color: var(--el-color-danger);
}

.warning-high {
  color: var(--el-color-warning);
}

.warning-tag {
  margin-left: 4px;
}

.mb-20 {
  margin-bottom: 20px;
}

.el-alert {
  margin-bottom: 16px;
}
</style>